package drone.iqgc.service ;

import java.util.LinkedHashMap ;
import java.util.List ;

import org.springframework.beans.factory.annotation.Autowired ;
import org.springframework.transaction.annotation.Transactional ;

import com.github.pagehelper.Page ;
import com.github.pagehelper.PageHelper ;

import drone.basis.base.BaseResult ;
import drone.basis.meta.MethodMeta ;
import drone.basis.util.PageUtil ;
import drone.basis.util.SqlUtil ;
import drone.basis.util.StringUtil ;
import drone.iqgc.dao.IGlobalDao ;

@Transactional
public class GlobalService
{

	@Autowired
	private IGlobalDao globalDao ;

	@MethodMeta ( name = "汇总字段" , description = "根据条件汇总指定字段的数量" )
	public Integer record (
			String sqlInfo
	) throws Exception
	{
		if ( StringUtil.isEmpty ( sqlInfo ) || sqlInfo.indexOf ( "from" ) < 0 )
		{
			return 0 ;
		}
		sqlInfo = "select count(*) as record " + sqlInfo.substring ( sqlInfo.indexOf ( "from" ) , sqlInfo.length ( ) ) ;

		List < LinkedHashMap < String , Object > > result = globalDao.query ( sqlInfo ) ;

		return new Integer ( result.get ( 0 ).get ( "record" ).toString ( ) ) ;
	}

	@MethodMeta ( name = "全局查询" , description = "按SQL语句查询返回Object集合列表对象" )
	public BaseResult < LinkedHashMap < String , Object > > search (
			String sqlInfo ,
			PageUtil pageUtil
	) throws Exception
	{
		if ( StringUtil.isEmpty ( sqlInfo ) )
		{
			return null ;
		}

		Page < ? > page = PageHelper.startPage ( pageUtil.getPageIndex ( ) , pageUtil.getPageSize ( ) , true ) ;
		List < LinkedHashMap < String , Object > > resultList = globalDao.query ( SqlUtil.filter ( sqlInfo ) ) ;

		pageUtil.setPageRecord ( new Long ( page.getTotal ( ) ).intValue ( ) ) ;
		pageUtil.allocation ( ) ;

		BaseResult < LinkedHashMap < String , Object > > baseResult = new BaseResult < LinkedHashMap < String , Object > > ( resultList , pageUtil ) ;
		return baseResult ;
	}

	@MethodMeta ( name = "整体更新" , description = "按SQL语句执行dml更新语句" )
	public BaseResult < Object > execute (
			String sqlInfo
	) throws Exception
	{
		int result = globalDao.modify ( sqlInfo ) ;
		return new BaseResult < Object > ( result ) ;
	}

}
